//
//  AppDelegate.m
//  huashiedu
//
//  Created by oceans on 2018/7/24.
//  Copyright © 2018年 hema. All rights reserved.
//

#import "AppDelegate.h"
#import "TabbarViewController.h"
#import "OAuthAPI.h"
#import <AFNetworkReachabilityManager.h>
#import <AlipaySDK/AlipaySDK.h>
#import <RongIMKit/RongIMKit.h>
#import "TestViewController.h"
#import "HttpRequest.h"
#import "PaymentModel.h"
#import "BootPageViewController.h"
#import "ClassTypeObject.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import <XHLaunchAd.h>
#import "NavigationViewController.h"

@interface AppDelegate () <RCIMUserInfoDataSource>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"is_token_loading"];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    [OAuthAPI getAccessToken];
    
    [UserModel shared];
    
    [[ClassTypeObject shared] requestClassTypes:nil];
    
    //iOS10特有
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    // 必须写代理，不然无法监听通知的接收与点击
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            // 点击允许
            NSLog(@"注册成功");
            [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                NSLog(@"%@", settings);
            }];
        } else {
            // 点击不允许
            NSLog(@"注册失败");
        }
    }];
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    [[RCIM sharedRCIM] initWithAppKey:@"y745wfm8yj61v"];
    [[RCIM sharedRCIM] setEnableMessageAttachUserInfo:YES];
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
//    [[RCIM sharedRCIM] setDisableMessageAlertSound:YES];
    
//    [WXApi registerApp:wxappkey];
    [WXApi registerApp:wxappkey enableMTA:YES];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi || status == AFNetworkReachabilityStatusReachableViaWWAN) {
            [OAuthAPI getAccessToken];
            [[ClassTypeObject shared] requestClassTypes:nil];
        }
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    TabbarViewController *tab = [[TabbarViewController alloc] init];
    NavigationViewController *navi = [[NavigationViewController alloc] initWithRootViewController:tab];
    navi.navigationBar.tintColor = [UIColor blackColor];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor clearColor]} forState:UIControlStateHighlighted];
    self.window.rootViewController = navi;
    self.root = navi;
    [self.window makeKeyAndVisible];
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"showed_boot_image"] == NO) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"showed_boot_image"];
        BootPageViewController *controller = [[BootPageViewController alloc] init];
        [self.root presentViewController:controller animated:NO completion:nil];
    }else {
        NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:@"splash_url"];
        if (url && url.length > 0) {
            XHLaunchImageAdConfiguration *config = [[XHLaunchImageAdConfiguration alloc] init];
            config.duration = 3;
            config.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
            config.imageNameOrURLString = url;
            config.skipButtonType = SkipTypeTimeText;
            config.imageOption = XHLaunchAdImageDefault;
            //图片填充模式
            config.contentMode = UIViewContentModeScaleAspectFill;
            //显示动画
            config.showFinishAnimate = ShowFinishAnimateFadein;
            [XHLaunchAd imageAdWithImageAdConfiguration:config];
        }
    }
    
//    TestViewController *controller = [[TestViewController alloc] init];
//    self.window.rootViewController = controller;
//    [self.window makeKeyAndVisible];
    
    // 远程推送的内容
    NSDictionary *remoteNotificationUserInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (remoteNotificationUserInfo) {
        NSLog(@"%@", remoteNotificationUserInfo);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:[remoteNotificationUserInfo description] preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
    }
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    application.applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - pushnotifacation

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"                                  withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

#pragma mark - userinfo

- (void)getUserInfoWithUserId:(NSString *)userId completion:(void (^)(RCUserInfo *))completion {
    
    [HttpRequest getURL:[NSString stringWithFormat:kget_ry_userinfo, userId] paras:nil showProgress:NO successful:^(id  _Nullable result) {
        
        NSDictionary *dic = result[@"data"];
        RCUserInfo *info = [[RCUserInfo alloc] initWithUserId:userId name:dic[@"nickname"] portrait:dic[@"avatar"]];
        completion(info);
    } failed:nil];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"");
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSLog(@"");
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
    NSLog(@"");
}

#pragma mark - open url

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    
    //微信登录
    //wx7d806c4b152327c1://oauth?code=0712XgbT0nrAyX1ybucT0GU7bT02XgbY&state=
    //微信分享给好友
    //wx7d806c4b152327c1://platformId=wechat
    //微信分享到朋友圈
    //wx7d806c4b152327c1://platformId=wechat
    //微信支付成功
    //wx7d806c4b152327c1://pay/?returnKey=&ret=0
    //支付宝成功
    //huashiedu://safepay/?
    NSLog(@"%@", url);
    NSLog(@"%@", options);
    if ([url.absoluteString hasPrefix:wxappkey]) {
        if ([url.host isEqualToString:@"oauth"]) {
            return [WXApi handleOpenURL:url delegate:[UserModel shared]];
        }
        return [WXApi handleOpenURL:url delegate:self];
    }
    /*{
     memo = "";
     result = "{\"alipay_trade_app_pay_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"app_id\":\"2018050502637826\",\"auth_app_id\":\"2018050502637826\",\"charset\":\"UTF-8\",\"timestamp\":\"2018-09-13 16:47:00\",\"total_amount\":\"0.01\",\"trade_no\":\"2018091322001408800543283705\",\"seller_id\":\"2088131113850384\",\"out_trade_no\":\"201180913604072534\"},\"sign\":\"Cs7P6lPtZKhdoGzRl5iivxPkrLnOD/wJqWapUeuwRKKo0wCnoUmDk4SUk+Pd0XyUa1m6n2bCiZraecffCv0LvlpILu19y31aFWeJlLKVtCPNgYX+EBcVJXiRs0n72rGhb4STlt+2C8bgEMT58XBvihDyVtWLFIFVXnJ37nl/t556dQtecJGtxBPYdaGOrN8/A1f2MqtZufHosV0u/41BSxOY4QODrKVX+0DUXvlrmkV0iCEYdndOC4X+K/ydeu+P9okoQTOKx17lWZEng2h0tIbE5AvjAuv+QV6jl4WGo78m1KzD0EAXUSvRgC1u5kGS8ABtkaizG2XL+EXOaA791g==\",\"sign_type\":\"RSA2\"}";
     resultStatus = 9000;
     }*/
    //取消
    /*result = {
     memo = "\U7528\U6237\U4e2d\U9014\U53d6\U6d88";
     result = "";
     resultStatus = 6001;
     }*/
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            if ([[resultDic objectForKey:@"resultStatus"] intValue] != 9000) {
                [[PaymentModel shared] payFailed];
            }else {
                [[PaymentModel shared] payFinished];
            }
        }];
    }
    if ([url.host isEqualToString:@"qzapp"]) {
        [TencentOAuth HandleOpenURL:url];
    }
    return YES;
}

#pragma mark - wxapidelegate

- (void)onResp:(BaseResp *)resp {
    NSLog(@"%@", resp);
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        switch (resp.errCode) {
            case WXSuccess:
                [[PaymentModel shared] payFinished];
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                break;
                
            default:
                [[PaymentModel shared] payFailed];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                break;
        }
    }
}

- (void)onReq:(BaseReq *)req {
    NSLog(@"%@", req);
}

#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"huashiedu"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    
                    /*
                     Typical reasons for an error here include:
                     * The parent directory does not exist, cannot be created, or disallows writing.
                     * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                     * The device is out of space.
                     * The store could not be migrated to the current model version.
                     Check the error message to determine what the actual problem was.
                    */
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }
    
    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end
